import { getVisitList } from '../../../utils/visit'
Page({
  data: {
    // 搜索相关
    searchKeyword: '',
    isSearchFocused: false,
    showSearchType: false,
    searchType: 'Date', 
    searchPlaceholder: '请输入日期',
    id: '',

    // 日期相关
    showDatePicker: false,
    dateLevel: 'year', // 默认展示年份选择, 可选值：year, month, day

    years: [],
    months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    days: [],
    yearIndex: 0, // 默认为当前年份索引（最近11年中的最后一年）
    monthIndex: 0,
    dayIndex: 0,
    selectedYear: 0,
    selectedMonth: 0,
    selectedDay: 0,
    dateDisplay: '', // 显示的日期文本

    init: true,

    // 搜索结果
    searchResults: [],
    filteredResults: [],
    hasSearched: false,
    isLoading: false,

    // 其他状态
    pageNum: 1,
    pageSize: 15,
    hasMoreData: true,
    totalCount: 0,

  },

  onLoad: function (options) {
    const id = options.id;
    console.log('家庭id',id)
    this.setData({
      id: id
    });
    // 页面初始化加载数据
    this.loadInitialData(id);
    this.initDatePicker();
  },

  // 初始化日期选择器数据
  initDatePicker: function () {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = currentYear - 10; i <= currentYear; i++) {
      years.push(i);
    }
    // 确保默认选中的年份索引在有效范围内
    const defaultYearIndex = Math.max(0, Math.min(years.length - 1, years.length - 1));
    this.setData({
      years: years,
      yearIndex: defaultYearIndex
    });
    this.updateDays();
  },

  // 根据年月更新天数
  updateDays: function () {
    const year = this.data.years[this.data.yearIndex] || new Date().getFullYear();
    const month = this.data.months[this.data.monthIndex] || 1;
    const daysInMonth = new Date(year, month, 0).getDate();

    const days = [];
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(i);
    }

    // 保持当前选择的日期索引，如果超出范围则设置为最大值
    const currentDayIndex = this.data.dayIndex;
    const newDayIndex = Math.min(currentDayIndex, days.length - 1);

    this.setData({
      days: days,
      dayIndex: newDayIndex
    });
  },

  // 选择搜索类型
  selectSearchType: function (e) {
    const type = e.currentTarget.dataset.type;
    let placeholder = '';

    // 根据不同类型设置不同的占位符
    if (type === 'Date') {
      placeholder = '请选择日期';
    }

    this.setData({
      searchType: type,
      showSearchType: false,
      searchPlaceholder: placeholder,
      searchKeyword: '' // 切换类型时清空关键词
    });
  },

  // 显示日期选择器
  showDatePickerModal: function () {
    this.setData({
      showDatePicker: true
    });
  },

  // 隐藏日期选择器
  hideDatePicker: function () {
    this.setData({
      showDatePicker: false
    });
  },

  // 切换日期选择级别
  switchDateLevel: function (e) {
    const level = e.currentTarget.dataset.level;
    if (level === 'year') {
      this.setData({
        selectedMonth: 0,
        selectedDay: 0
      })
    }
    if (level === 'month') {
      this.setData({
        selectedDay: 0
      })
    }
    this.setData({
      dateLevel: level
    });
  },

  // 年份变化
  onYearChange: function (e) {
    const val = e.detail.value;
    // 确保索引在有效范围内
    const newIndex = Math.max(0, Math.min(val[0] || 0, this.data.years.length - 1));
    this.setData({
      yearIndex: newIndex,
      dateLevel: 'year'
    });
    this.updateDays();
  },

  // 月份变化
  onMonthChange: function (e) {
    const val = e.detail.value;
    // 确保索引在有效范围内
    const newYearIndex = Math.max(0, Math.min(val[0] || 0, this.data.years.length - 1));
    const newMonthIndex = Math.max(0, Math.min(val[1] || 0, this.data.months.length - 1));
    this.setData({
      yearIndex: newYearIndex,
      monthIndex: newMonthIndex,
    });
    this.updateDays();
  },

  // 日期变化
  onDayChange: function (e) {
    const val = e.detail.value;
    // 确保索引在有效范围内
    const newYearIndex = Math.max(0, Math.min(val[0] || 0, this.data.years.length - 1));
    const newMonthIndex = Math.max(0, Math.min(val[1] || 0, this.data.months.length - 1));
    const newDayIndex = Math.max(0, Math.min(val[2] || 0, this.data.days.length - 1));
    this.setData({
      yearIndex: newYearIndex,
      monthIndex: newMonthIndex,
      dayIndex: newDayIndex,
    });
  },

  // 确认日期选择
  confirmDateSelection: function () {
    const { years, months, days, yearIndex, monthIndex, dayIndex, dateLevel } = this.data;
    const year = years[yearIndex];

    this.setData({
      selectedYear: year
    })

    let dateText = `${year}年`;
    let dateParam = `${year}`;

    if (dateLevel === 'month' || dateLevel === 'day') {
      const month = months[monthIndex];
      this.setData({
        selectedMonth: month
      })
      const monthStr = month < 10 ? `0${month}` : `${month}`;
      dateText += `${month}月`;
      dateParam += `-${monthStr}`;
    }

    if (dateLevel === 'day') {
      const day = days[dayIndex];
      this.setData({
        selectedDay: day
      })
      const dayStr = day < 10 ? `0${day}` : `${day}`;
      dateText += `${day}日`;
      dateParam += `-${dayStr}`;
    }
    // console.log(this.data.selectedYear)
    // console.log(this.data.selectedMonth)
    // console.log(this.data.selectedDay)

    this.setData({
      dateDisplay: dateText,
      searchKeyword: dateParam,
      showDatePicker: false
    });

    // 自动执行搜索
    this.onSearch();
  },

  // 清除日期选择
  clearDateSelection: function () {
    this.setData({
      dateDisplay: '',
      searchKeyword: '',
      showDatePicker: false
    });
  },

  // 初始化数据加载
  loadInitialData: function (id) {
    // 这里可以加载初始数据
    // 模拟数据
    const data = {
      'Year': 0,
      'Month': 0,
      'Day': 0,
      'FamilyUid': id,
      'PageNum': 1,
      'PageSize': 200
    }
    console.log('初始化数据请求',data)
    getVisitList(data).then(res => {
      console.log('初始化数据',res)
      if (res && res.code === 200) {
        this.setData({
          filteredResults: res.data,
          totalCount: res.total || res.data.length,
          hasMoreData: res.data.length >= this.data.pageSize,
          isLoading: false
        });
      }
    })

    // this.setData({
    //   searchResults: mockData,
    //   filteredResults: mockData.slice(0, this.data.pageSize),
    //   totalCount: mockData.length,
    //   hasMoreData: mockData.length > this.data.pageSize
    // });
  },

  // 点击搜索图标切换搜索类型
  toggleSearchType: function () {
    this.setData({
      showSearchType: !this.data.showSearchType
    });
  },

  // 隐藏搜索类型下拉框
  hideSearchType: function () {
    this.setData({
      showSearchType: false
    });
  },

  // 阻止事件冒泡
  stopPropagation: function () { },

  // 搜索框输入事件
  onSearchInput: function (e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索框获取焦点
  onInputFocus: function () {
    this.setData({
      isSearchFocused: true
    });

    // 只有在区域搜索时才显示区域选择器
    if (this.data.searchType === 'Area') {
      this.showAreaPicker();
    } else if (this.data.searchType === 'Date') {
      // 显示日期选择器
      this.showDatePickerModal();
    }
  },

  // 搜索框失去焦点
  onSearchBlur: function () {
    this.setData({
      isSearchFocused: false
    });
  },

  // 执行搜索
  onSearch: function () {
    const keyword = this.data.searchKeyword.trim();

    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isLoading: true,
      init: false,
      hasSearched: true,
      showDatePicker: false // 搜索时隐藏日期选择器
    });

    // 构建API请求参数
    let params = {
      'PageNum': 1,
      'PageSize': 200,
      'Year': this.data.selectedYear,
      'Month': this.data.selectedMonth,
      'Day': this.data.selectedDay,
      'FamilyUid': this.data.id
    };

    console.log(params)

    // 调用API进行搜索
    getVisitList(params).then(res => {
      console.log('搜索结果:', res);

      if (res && res.code === 200 && res.data) {
        this.setData({
          filteredResults: res.data,
          totalCount: res.total || res.data.length,
          hasMoreData: res.data.length >= this.data.pageSize,
          isLoading: false
        });

        // 如果没有结果，显示提示
        if (res.data.length === 0) {
          wx.showToast({
            title: '未找到匹配的记录',
            icon: 'none'
          });
        }
      } else {
        this.setData({
          filteredResults: [],
          isLoading: false
        });

        wx.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      }

      // 震动反馈
      wx.vibrateShort({
        type: 'medium'
      });
    }).catch(err => {
      console.error('搜索出错:', err);
      this.setData({
        filteredResults: [],
        isLoading: false
      });

      wx.showToast({
        title: '搜索失败，请重试',
        icon: 'none'
      });
    });
  },

  // 点击搜索结果项
  onSelectItem: function (e) {
    const id = e.currentTarget.dataset.id;
    // 这里可以跳转到详情页或执行其他操作
    console.log('选择了人员ID:', id);
    //跳转到详情页
    wx.navigateTo({
      url: `/pages/visit/detail/detail?id=${id}`,
      success: () => {
        console.log('跳转到探访记录列表页成功');
      },
      fail: (err) => {
        console.error('跳转到探访记录列表页失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });

  },

  // 跳转到添加页面
  // goToAddPage: function () {
  //   wx.navigateTo({
  //     url: '/pages/visit/edit/edit',
  //     success: () => {
  //       console.log('跳转到添加页面成功');
  //     },
  //     fail: (err) => {
  //       console.error('跳转到添加页面失败:', err);
  //       wx.showToast({
  //         title: '页面跳转失败',
  //         icon: 'none'
  //       });
  //     }
  //   });
  // },

});
